<!--
 * @Author: ZhaoZhiqi
 * @Date: 2024-04-30 16:17:41
 * @LastEditors: ZhaoZhiqi
 * @LastEditTime: 2024-09-29 21:44:38
 * @Description: VIP编辑
 * @FilePath: \parking-mini\src\pages\vip_edit.vue
-->
<template>
    <div class="container">
        <div class="header" :style="{ backgroundImage: `url(${imgs.vip_header})` }"></div>
        <div class="title1">{{ plan.name || "" }}</div>
        <div class="title2">{{ plan.dadaParkName || "" }}</div>
        <!-- <div class="location" @click="link('/pages/parking_list')">
            <img :src="imgs.location" />
            <span>适用停车场</span>
        </div> -->
        <div class="card">
            <img class="circle" :src="imgs.circle" />
            <div class="title">请选择{{ card_id ? "续费" : "开卡" }}时长</div>
            <div class="item">
                <div class="label">月卡时长：</div>
                <div class="form-value">
                    <u-number-box v-model="number"></u-number-box>
                    <span style="margin-left: 20rpx">月</span>
                </div>
            </div>
            <div v-if="plan.activityContents && plan.activityContents.length" class="item discount" style="height: auto">
                <div class="label">活动优惠：</div>
                <div class="form-value">
                    <div class="discount-text" v-for="itm in plan.activityContents" :key="itm.id">办卡{{ itm.overMonth }}个月及以上可赠送{{ itm.donateMonth }}个月</div>
                </div>
            </div>
            <div class="item">
                <div class="label">开始时间：</div>
                <div class="form-value">{{ card_id ? beginTime2 : beginTime }}</div>
            </div>
            <div class="item">
                <div class="label">到期时间：</div>
                <div class="form-value">{{ card_id ? endTime2 : endTime }}</div>
            </div>
            <div class="item">
                <div class="label">支付金额：</div>
                <div class="form-value">{{ plan.amount * number }}元</div>
            </div>
        </div>
        <div class="card">
            <img class="circle" :src="imgs.circle" />
            <div class="title">{{ card_id ? "" : "请确认需要开卡的" }}车牌信息</div>
            <div class="item">
                <div class="select" @click="showCarNumberModal">
                    <div class="select-name">{{ carNumber || "请选择车牌号码" }}</div>
                    <img v-if="!card_id" :src="imgs.select" />
                </div>
            </div>
        </div>
        <div class="card">
            <img class="circle" :src="imgs.circle" />
            <div class="title">{{ card_id ? "" : "请完善" }}开卡人信息</div>
            <div class="item">
                <div class="label">姓名：</div>
                <div class="form-value">
                    <input v-model="fullName" :disabled="card_id" class="form-input" placeholder="请输入姓名" />
                </div>
            </div>
            <div class="item">
                <div class="label">身份证号：</div>
                <div class="form-value">
                    <input v-model="idNumber" :disabled="card_id" class="form-input" placeholder="请输入身份证号" />
                </div>
            </div>
            <div class="item">
                <div class="label">手机号码：</div>
                <div class="form-value">{{ phone }}</div>
            </div>
            <div v-if="!card_id || plan.workNumber" class="item">
                <div class="label">工号：</div>
                <div class="form-value">
                    <input v-model="workNumber" :disabled="card_id" class="form-input work-number" placeholder="蓝思科技员工必填, 否则无法进入外岗" placeholder-class="work-number" />
                </div>
            </div>
        </div>

        <div v-if="card_id" class="button" @click="confirm">确定</div>
        <div v-else-if="plateList.length && plateList[0].length" class="button" @click="confirm">确定</div>
        <div v-else class="button" @click="link('/pages/numberplate')">暂无可用车牌，去新增</div>

        <u-picker :show="visible" :columns="plateList" @cancel="visible = false" @confirm="plateChange"></u-picker>

        <Contract :visible="contractVisible" :info="info" @close="contractVisible = false" @success="onSuccess"></Contract>
    </div>
</template>
<script>
import moment from "moment";
import CryptoJs from "crypto-js";
import md5 from "js-md5";
import { Base64 } from "js-base64";
import Contract from "../components/Contract.vue";
import { createOrderAPI, buyVipAPI, renewOrderAPI, updateVipAPI, getFreeCarNumberListAPI, getVipTypeDetailAPI, getAcountAPI, getAcountTokenAPI, getVipCardDetailAPI } from "../api/api";
const app = getApp();

export default {
    components: { Contract },
    data() {
        let today = moment().startOf("day");
        let phone = wx.getStorageSync("parking_phone");
        return {
            moment,
            imgs: app.globalData.imgs,
            visible: false,
            authToken: "",

            plan: {}, // 月卡详情
            plateList: [],
            flag: false, // 支付状态
            // form
            number: 1, // 商品数量
            today: moment().startOf("day"),
            beginTime: today.format("YYYY-MM-DD HH:mm:ss"),
            tradeNo: "", // 订单号
            carNumber: "", // 车牌号
            fullName: "", // 姓名
            idNumber: "", // 身份证
            contractFilePath: "", // 合同文件url
            phone,
            workNumber: "",

            // 续费相关参数
            beginTime2: "",

            // 页面参数
            id: "",
            card_id: "", // 月卡id 用于续费

            contractVisible: false,
        };
    },
    computed: {
        donateMonth() {
            let n = 0;
            if (this.plan && this.plan.activityContents && this.plan.activityContents.length) {
                this.plan.activityContents.forEach((item) => {
                    if (this.number >= item.overMonth) {
                        n = item.donateMonth;
                    }
                });
            }
            return n;
        },
        // 开卡结束时间
        endTime() {
            return moment(this.today)
                .add(30 * (this.number + this.donateMonth) - 1, "days")
                .endOf("days")
                .format("YYYY-MM-DD HH:mm:ss");
        },
        // 续费结束时间
        endTime2() {
            return moment(this.beginTime2)
                .add(30 * (this.number + this.donateMonth) - 1, "days")
                .endOf("days")
                .format("YYYY-MM-DD HH:mm:ss");
        },
        info() {
            return {
                dadaParkName: this.plan.dadaParkName,
                fullName: this.fullName,
                idNumber: this.idNumber,
                phone: this.phone,
                carNumber: this.carNumber,
                beginTime: moment(this.card_id ? this.beginTime2 : this.beginTime).format("YYYY-MM-DD"),
                endTime: moment(this.card_id ? this.endTime2 : this.endTime).format("YYYY-MM-DD"),
                number: this.number,
                price: this.plan.amount,
            };
        },
    },
    onShareAppMessage() {},
    onLoad(options) {
        let id = options.id;
        let card_id = options.card_id;
        this.id = id;
        this.card_id = card_id;

        // 续费
        if (card_id) {
            wx.setNavigationBarTitle({ title: "续费信息填写" });
            getVipCardDetailAPI({ id: card_id }).then((res) => {
                this.plan = res;

                // 数据回填
                this.plan.name = res.cardName;
                this.carNumber = res.carNumber;
                this.fullName = res.fullName;
                this.idNumber = res.idNumber;
                this.workNumber = res.workNumber;
                this.beginTime2 = moment(moment(res.endTime).valueOf() + 1000).format("YYYY-MM-DD HH:mm:ss");
            });
        }
        // 开卡
        else {
            getVipTypeDetailAPI({ id }).then((res) => {
                this.plan = res;
            });
        }

        this.getAuthToken();
    },
    onShow() {
        // 续费不能更换车牌
        if (!this.card_id) {
            getFreeCarNumberListAPI({
                openId: wx.getStorageSync("parking_openid"),
                cardId: this.id,
            }).then((res) => {
                let plateList = res || [];
                this.plateList = [plateList.map((item) => item.carNumber)];
            });
        }
    },
    methods: {
        showCarNumberModal() {
            if (this.card_id) return false;
            this.visible = true;
        },
        // 路由跳转
        link(url, params) {
            uni.$u.route(url, params);
        },
        confirm() {
            // 校验表单
            if (!this.carNumber) {
                wx.showToast({
                    title: "请选择车牌号",
                    icon: "none",
                });
                return false;
            } else if (!this.fullName) {
                wx.showToast({
                    title: "请输入姓名",
                    icon: "none",
                });
                return false;
            } else if (!this.idNumber) {
                wx.showToast({
                    title: "请输入身份证号",
                    icon: "none",
                });
                return false;
            } else if (this.idNumber.length !== 18) {
                console.log(this.idNumber.length);
                wx.showToast({
                    title: "请输入正确身份证号",
                    icon: "none",
                });
                return false;
            }
            this.contractVisible = true;
        },
        // 选择车牌
        plateChange(e) {
            this.carNumber = e.value[0];
            this.visible = false;
        },
        // 获取合同url成功
        onSuccess(url) {
            this.contractVisible = false;
            this.contractFilePath = url;
            this.pay();
        },
        // 加密
        getAuthData(phoneNumber, password) {
            let key_str = md5(phoneNumber);
            let key = CryptoJs.enc.Utf8.parse(key_str);
            let AESPass = CryptoJs.AES.encrypt(password, key, {
                mode: CryptoJs.mode.ECB,
                padding: CryptoJs.pad.Pkcs7,
            });
            let pass = AESPass.toString();
            return Base64.encode(phoneNumber + ":" + pass).replace(/[\r\n]/g, "");
        },
        // 获取authToken
        getAuthToken() {
            getAcountAPI()
                .then((res) => {
                    let authData = this.getAuthData(res.username, res.password);
                    return getAcountTokenAPI({ authData });
                })
                .then((response) => {
                    this.authToken = response.token;
                });
        },
        pay() {
            if (this.flag) return false;
            this.flag = true;
            wx.showLoading({
                title: "支付中...",
            });

            let createApi = this.card_id ? renewOrderAPI : createOrderAPI;
            // 创建/续费订单
            createApi(
                {
                    token: wx.getStorageSync("dada_token"),
                    openid: wx.getStorageSync("parking_openid"),
                    plate_number: this.carNumber,
                    fullName: this.fullName,
                    cardId: this.card_id ? this.plan.cardId : this.plan.id,
                    num: this.number,
                    name: this.plan.name,
                    dadaCardKindId: this.plan.dadaCardKindId,
                    donateMonth: this.donateMonth || null,
                    workNumber: this.workNumber,
                },
                (err) => {
                    if (err && err.code === 414) {
                        // 414 超过活动时间
                        wx.showToast({
                            title: `活动已结束，请返回月卡列表重新办理"`,
                            icon: "none",
                        });
                        setTimeout(() => {
                            const pages = getCurrentPages();
                            const page = pages[pages.length - 1];
                            uni.redirectTo({
                                url: decodeURIComponent(page.$page.fullPath),
                            });
                        }, 1500);
                    } else {
                        wx.showToast({
                            title: err ? err.msg : "未知错误",
                            icon: "none",
                        });
                    }
                    return Promise.reject(err);
                }
            )
                .then((res) => {
                    let tradeNo = res.tradeNo;
                    let params = {
                        openId: wx.getStorageSync("parking_openid"),
                        number: this.number,
                        beginTime: this.card_id ? this.beginTime2 : this.beginTime,
                        endTime: this.card_id ? this.endTime2 : this.endTime,
                        tradeNo,
                        carNumber: this.carNumber,
                        fullName: this.fullName,
                        idNumber: this.idNumber,
                        createTime: res.createTime,
                        cardId: this.card_id ? this.plan.cardId : this.plan.id,
                        contractFilePath: this.contractFilePath,
                        dadaCardKindId: res.dadaCardKindId,
                        payAmount: this.plan.amount * this.number,
                        donateMonth: this.donateMonth || null,
                        // token: wx.getStorageSync("dada_token"),
                        token: this.authToken,
                        workNumber: this.workNumber,
                    };

                    // 将订单存入缓存
                    if (this.card_id) {
                        params.id = this.plan.id; // 用户月卡id 续费时传
                        wx.setStorageSync(`unpaid_trade_no_renew_${tradeNo}`, JSON.stringify(params));
                    } else {
                        wx.setStorageSync(`unpaid_trade_no_normal_${tradeNo}`, JSON.stringify(params));
                    }
                    console.log("params", params);

                    // 小程序支付
                    wx.requestPayment({
                        timeStamp: res.timeStamp,
                        nonceStr: res.nonceStr,
                        package: res.package,
                        signType: res.signType,
                        paySign: res.paySign,
                        success: (res) => {
                            this.flag = false;

                            wx.showLoading({
                                title: "订单生成中...",
                            });

                            // 购买/更新月卡
                            let updateApi = this.card_id ? updateVipAPI : buyVipAPI;
                            updateApi(params).then((res) => {
                                // 调用接口成功购买月卡后，删掉缓存中对应的tradeNo，renew是续费缓存
                                if (this.card_id) {
                                    wx.removeStorageSync(`unpaid_trade_no_renew_${tradeNo}`);
                                } else {
                                    wx.removeStorageSync(`unpaid_trade_no_normal_${tradeNo}`);
                                }

                                wx.showToast({
                                    title: this.card_id ? "续费月卡成功" : "开通月卡成功",
                                    icon: "success",
                                });
                                setTimeout(() => {
                                    uni.navigateBack();
                                }, 1500);
                            });
                        },
                        fail: (err) => {
                            this.flag = false;
                            wx.hideLoading();
                            // 删掉缓存中对应的tradeNo
                            if (this.card_id) {
                                wx.removeStorageSync(`unpaid_trade_no_renew_${tradeNo}`);
                            } else {
                                wx.removeStorageSync(`unpaid_trade_no_normal_${tradeNo}`);
                            }
                            console.log("支付失败", err);
                        },
                    });
                })
                .catch((err) => {
                    console.log(err);
                    this.flag = false;
                });
        },
    },
};
</script>
<style scoped lang="scss">
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 200rpx;
    padding-bottom: 150rpx;
    .header {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 267rpx;
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
    }
    .title1 {
        color: #fff;
        font-size: 34rpx;
        line-height: 1;
        font-weight: bold;
        position: absolute;
        left: 200rpx;
        top: 70rpx;
        z-index: 2;
    }
    .title2 {
        color: #fff;
        font-size: 28rpx;
        line-height: 1;
        position: absolute;
        left: 200rpx;
        top: 120rpx;
        z-index: 2;
    }
    .location {
        display: flex;
        align-items: center;
        color: #fff;
        font-size: 24rpx;
        left: 1;
        position: absolute;
        top: 30rpx;
        right: 60rpx;
        img {
            width: 30rpx;
            height: 30rpx;
            margin-right: 10rpx;
        }
    }
    .card {
        background-color: #fff;
        position: relative;
        z-index: 2;
        margin-bottom: 40rpx;
        width: 697rpx;
        box-sizing: border-box;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.1);
        border-radius: 24rpx;
        padding-left: 80rpx;
        padding-bottom: 20rpx;
        .circle {
            width: 32rpx;
            height: 32rpx;
            position: absolute;
            top: 37rpx;
            left: 37rpx;
        }
        .title {
            color: #000;
            font-size: 32rpx;
            line-height: 1;
            margin: 36rpx 0;
            font-weight: bold;
        }
        .item {
            height: 80rpx;
            display: flex;
            align-items: center;
            font-size: 32rpx;
            line-height: 1;
            width: 570rpx;
            &.discount {
                align-items: flex-start;
                padding-top: 20rpx;
                font-size: 24rpx;
                line-height: 1;
                .label {
                    color: #ff0000;
                    text-align: right;
                    box-sizing: border-box;
                    padding-right: 5px;
                }
                .form-value {
                    flex-direction: column !important;
                    align-items: flex-start !important;

                    .discount-text {
                        color: #ff0000;
                        margin-bottom: 20rpx;
                    }
                }
            }
            .label {
                flex: none;
                color: #333;
                width: 160rpx;
                text-align: justify;
            }
            .form-value {
                color: #333;
                display: flex;
                align-items: center;
                flex: auto;
                .form-input {
                    width: 100%;
                    padding: 10rpx 0;
                    border-bottom: 1rpx solid #e6e6e6;
                    color: #333;
                }
                .work-number {
                    font-size: 24rpx;
                    &::placeholder {
                        font-size: 24rpx;
                    }
                }
            }
            .select {
                width: 100%;
                color: #333333;
                font-size: 32rpx;
                line-height: 1;
                padding-bottom: 20rpx;
                border-bottom: 1rpx solid #e6e6e6;
                display: flex;
                justify-content: space-between;
                align-items: center;
                img {
                    width: 24rpx;
                    height: 24rpx;
                }
            }
        }
    }
    .button {
        position: fixed;
        bottom: 50rpx;
        margin-top: 30rpx;
        background-color: #009cff;
        width: 697rpx;
        height: 100rpx;
        border-radius: 50rpx;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 2;
    }
}
</style>
